<template>
  <div class="waitSite">
    <div class="list">
      <div
        class="item"
        v-for="(it, ind) in list"
        v-if="!it.printEnabled"
        :key="ind"
      >
        <div class="item-inner">
          <div class="num">{{ it.num }}</div>
          <div class="wait-info">
            <div class="site-name">{{ it.area }}</div>
            <div class="phone">手机号:{{ it.mobile ? it.mobile : "--" }}</div>
            <div>
              <el-tooltip
                class="item"
                effect="dark"
                :content="it.remark"
                placement="top"
              >
                <div class="remark">
                  <span>备注:{{ it.remark ? it.remark : "--" }}</span>
                </div>
              </el-tooltip>
            </div>

            <div class="time" v-if="it.addTime">
              排号时间:{{ new Date(it.addTime).Format("MM/dd hh:mm") }}
            </div>
          </div>
          <div class="btn-wrap">
            <span class="btn" @click.stop="toPrint(it)">打印排号单</span>
          </div>
        </div>
      </div>
    </div>
    <div id="qrcode" v-if="showQrcode" style="display: none"></div>
    <div class="patch-print">
      <el-popover placement="left" width="200" trigger="click">
        <el-table :data="list" max-height="250" :row-class-name="hideRow">
          <el-table-column
            width="100"
            property="num"
            label="单号"
          ></el-table-column>
          <el-table-column width="100" label="打印">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="warning"
                @click.stop="patchPrint(scope.row)"
                >补打</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button size="mini" type="primary" slot="reference"
          >排号单补打</el-button
        >
      </el-popover>
    </div>
  </div>
</template>
<script>
import emitter from "@/bus/index";

export default {
  name: "waitSite",
  props: ["storeId", "storeName"],
  data() {
    return {
      list: [],
      showQrcode: true,
      timer: null,
      canClick: true,
    };
  },
  methods: {
    convertTo1Bit(imageData, width, height) {
      const bitmap = [];
      for (let y = 0; y < height; y++) {
        let byte = 0,
          bits = 0;
        for (let x = 0; x < width; x++) {
          const idx = (y * width + x) * 4;
          const r = imageData[idx],
            g = imageData[idx + 1],
            b = imageData[idx + 2];
          const isBlack = r + g + b < 200; // 简单二值化
          byte |= (isBlack ? 1 : 0) << (7 - bits);
          bits++;
          if (bits === 8) {
            bitmap.push(byte);
            byte = 0;
            bits = 0;
          }
        }
        if (bits > 0) bitmap.push(byte); // 补足末尾字节
      }
      return bitmap;
    },
    generateBitmapCommand(bitmapData, width, height) {
      const bytesPerLine = Math.ceil(width / 8);
      const xL = bytesPerLine % 256;
      const xH = Math.floor(bytesPerLine / 256);
      const yL = height % 256;
      const yH = Math.floor(height / 256);
      // 指令格式: GS v 0 [xL xH yL yH] [位图数据]
      return [
        0x1d,
        0x76,
        0x30,
        0x00, // GS v 0
        xL,
        xH,
        yL,
        yH, // 宽度（字节数）和高度
        ...bitmapData, // 位图数据
      ];
    },
    generateEscStarCommand(bitmapData, width) {
      const bytesPerLine = Math.ceil(width / 8);
      return [
        0x1b,
        0x2a,
        0x21, // ESC * 33 (单密度位图)
        bytesPerLine % 256,
        bytesPerLine >> 8, // 每行字节数
        ...bitmapData,
      ];
    },
    //
    //
    hideRow({ row, index }) {
      if (!row.printEnabled) {
        return "hide-row";
      }
    },
    patchPrint(item) {
      this.toPrint(item);
    },
    toPrint(item) {
      if (!this.canClick) {
        return;
      }
      this.canClick = false;
      this.$http({
        url: "schedul/print",
        method: "POST",
        data: {
          id: item.id,
        },
      })
        .then((res) => {
          this.$http({
            url: "https://prod-api.huoxingy.com/wechat/member/net",
            method: "GET",
            params: {
              id: item.id,
            },
          })
            .then((codeRes) => {
              console.log("codeRes", codeRes);
              console.log("storeName", this.storeName);
              let array = [];
              array = array.concat([28, 38]); //打印汉字
              array = array.concat([29, 33, 17]); //汉字倍宽高
              array = array.concat([27, 97, 49]); //居中
              // array = array.concat(gbk("欢迎光临" + this.storeName));
              array = array.concat(gbk(this.storeName + "排号系统"));
              array = array.concat([10]); //换行
              array = array.concat([27, 100, 2]); //空格走纸
              array = array.concat([27, 97, 48]); //左
              array = array.concat([29, 33, 0]); //取消汉字倍宽高
              array = array.concat(gbk("排位号:："));
              array = array.concat([29, 33, 17]);
              array = array.concat(gbk(item.num));
              array = array.concat([10]); //换行
              array = array.concat([29, 33, 0]);
              array = array.concat([27, 33, 0]); //取消加粗
              // array = array.concat(
              //   gbk("取号时间:：" + new Date(item.addTime).Format("MM/dd-hh:mm"))
              // );
              array = array.concat(gbk("区域:：" + item.area));
              array = array.concat([10]); //换行
              array = array.concat(
                gbk("取号时间:：" + new Date().Format("MM/dd-hh:mm"))
              );
              // array = array.concat([10]); //换行
              // array = array.concat(gbk("操作人员:：" + item.empName));
              array = array.concat([10]); //换行
              array = array.concat([27, 100, 2]); //空格走纸
              array = array.concat([27, 97, 49]); //居中
              //qrcode start
              try {
                const qrcode = new QRCode(document.getElementById("qrcode"), {
                  text: `${codeRes.data}`,
                  width: 200,
                  height: 200,
                  colorDark: "#000000",
                  colorLight: "#ffffff",
                  correctLevel: QRCode.CorrectLevel.H, // 高容错率
                });
              } catch (error) {
                console.log("error", error);
              }
              setTimeout(() => {
                const canvas = document.querySelector("#qrcode canvas");
                const imageData = canvas
                  .getContext("2d")
                  .getImageData(0, 0, 200, 200);
                const bitmap = this.convertTo1Bit(imageData.data, 200, 200);
                const cmd = this.generateBitmapCommand(bitmap, 200, 200);
                console.log(cmd);
                array = array.concat(cmd);
                array = array.concat([10]); //换行
                array = array.concat([27, 100, 2]); //空格走纸
                //
                array = array.concat(gbk("扫码可查看当前排号信息"));
                array = array.concat([10]); //换行
                // array = array.concat(
                //   gbk("因排队人数较多，只能预留5分钟，请提前规划时间到店!")
                // );
                array = array.concat(
                  gbk("因排队人数较多，请留意现场叫号！")
                );
                array = array.concat([10]); //换行
                array = array.concat([27, 100, 2]); //空格走纸
                array = array.concat([27, 100, 2]); //空格走纸
                array = array.concat([27, 105]); //切纸
                console.log("array", array);
                try {
                  print_(
                    localStorage.getItem("printIdForSale")
                      ? localStorage.getItem("printIdForSale")
                      : "",
                    array
                  ); //小票打印
                  this.showQrcode = false;
                  setTimeout(() => {
                    this.showQrcode = true;
                  }, 100);
                } catch (error) {
                  console.log("error", error);
                }
                //
                setTimeout(() => {
                  this.canClick = true;
                }, 500);
                //
              }, 500);
              // qrcode end
            })
            .catch((err) => {
              setTimeout(() => {
                this.canClick = true;
              }, 500);
            });

          setTimeout(() => {
            this.getData();
          }, 250);
        })
        .catch((err) => {
          setTimeout(() => {
            this.canClick = true;
          }, 500);
        });
    },
    getData() {
      this.$http({
        url: "schedul/list",
        method: "POST",
        data: {
          storeId: this.storeId,
          type: 0,
        },
      }).then((res) => {
        this.list = res.data;
      });
    },
  },
  mounted() {
    emitter.emit("refreshWaitSite", 0);
    this.getData();
    this.timer = setInterval(() => {
      this.getData();
    }, 5000);
  },
  destroyed() {
    if (this.timer) {
      console.log("clear timer");
      clearInterval(this.timer);
    }
  },
};
</script>
<style lang="scss" scoped>
@import "./waitSite.scss";
.remark {
  max-width: 250px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  padding-bottom: 10px;
  cursor: pointer;
}
.patch-print {
  position: absolute;
  right: 20px;
  top: 5px;
}
</style>
<style lang="scss">
.el-tooltip__popper {
  width: 200px;
}
.el-table .hide-row {
  display: none !important;
}
</style>